package Thread;

import java.util.concurrent.Future;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import thread.springAsync.DaoService;

@RunWith(value = SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:application-springAsync.xml" })
public class SpringAsync {

	@Autowired
	private DaoService daoService;
	
	
	@Test
	public void testAsync() throws Exception {
		System.out.println("start");
		daoService.update();
		System.out.println("end");
		Thread.sleep(3000); // 因为junit结束会结束jvm，所以让它等会异步线程
	}
	
	/**
	 * 这些获取异步方法的结果信息，是通过不停的检查Future的状态来获取当前的异步方法是否执行完毕来实现的。 
	 * @parameter
	 * @return
	 * @throws
	 */
	@Test
	public void testAsyncMethodWithReturnType() throws Exception {
		System.out.println("start Asyncing...");
		Future<String> asyncMethodWithReturnType = daoService.asyncMethodWithReturnType();
		while(true){
			if (asyncMethodWithReturnType.isDone()) {  //判断是否执行完毕  
	            System.out.println("Result from asynchronous process - " + asyncMethodWithReturnType.get());  
	            break;  
	        }  
	        System.out.println("Continue doing something else. ");  
	        Thread.sleep(1000);
		}
		System.out.println("end Asynced....");
		Thread.sleep(3000); // 因为junit结束会结束jvm，所以让它等会异步线程
	}
	
	
	@Test
	public void testthrowException() throws Exception {
		System.out.println("start Asyncing...");
		daoService.throwException();
		System.out.println("end Asynced....");
		Thread.sleep(3000);
	}
}
